package edu.sandau.b230151.b23015101.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import edu.sandau.b230151.b23015101.service.BookService;
import edu.sandau.b230151.b23015101.respository.BookRespository;
import edu.sandau.b230151.b23015101.model.Book;
import java.util.UUID;

@Controller
@RequestMapping("book")
public class BookController {
    @Autowired
    private BookService BookService;
    @Autowired
    private BookRespository BookRespository;

    @RequestMapping("/list")
    public String list(ModelMap map, Book book){
        if("".equals(book.getName())){
            book.setName(null);
        }
        map.put("book",BookService.findAll(book));//从数据库取数据
        return "/book/list";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id){
        BookService.deleteById(id);
        return "redirect:/book/list";
    }
    @RequestMapping("create")
    public String create(){
        return "book/create";
    }

    @RequestMapping("save")
    public String save(Book s) {
        if(s.getId()==null||s.getId().isEmpty()){
            s.setId(UUID.randomUUID().toString());
            BookService.save(s);
        }
        else{
            BookService.update(s);
        }
        return "redirect:/book/list";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable String id,ModelMap map){
        Book s=BookService.getReferenceById(id);
        map.put("book",s);
        return "book/update";
    }

}
